package at.connectme.templating.service;

import at.connectme.exception.TemplatingException;
import at.newmedialab.ldpath.exception.LDPathParseException;
import at.newmedialab.lmf.ldpath.api.LDPathService;
import kiwi.core.api.triplestore.ResourceService;
import kiwi.core.model.rdf.*;

import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * User: Thomas Kurz
 * Date: 23.01.12
 * Time: 11:26
 */
@ApplicationScoped
public class TemplatingService {

	@Inject
	LDPathService ldPathService;

	@Inject
	ResourceService resourceService;

	private static final Pattern PATH_PATTERN = Pattern.compile("\\{([^\\{\\}]*)\\}",Pattern.CASE_INSENSITIVE);

	private static final String EMPTY_VALUE = "no value";

	public String process(String uri, String template) throws TemplatingException {

		//http://localhost:8080/connectme/cmf/service/templating/resource?template=%3Ch1%3ELabel%3A{%3Chttp%3A%2F%2Fwww.w3.org%2F2000%2F01%2Frdf-schema%23label%3E%3A%3Axsd%3Astring}%3C%2Fh1%3E&uri=http%3A%2F%2Flabs.newmedialab.at%2FRedBull%2Fresource%2FSaint_Nicolas_Tower
		try {
			KiWiResource resource = resourceService.createUriResource(uri);
    		StringBuffer result = new StringBuffer();
    		Matcher matcher = PATH_PATTERN.matcher(template);
    		while ( matcher.find() ) {
      			matcher.appendReplacement(result, getReplacement(matcher, resource));
    		}
    		matcher.appendTail(result);
    		return result.toString();
		} catch (Exception e) {
			e.printStackTrace();
			throw new TemplatingException();
		}
	}

	private String getReplacement(Matcher matcher, KiWiNode node) throws LDPathParseException {
		Collection<KiWiNode> nodes = ldPathService.pathQuery(node,matcher.group(1),null);
		if(nodes.isEmpty()) return EMPTY_VALUE;
		KiWiNode n = nodes.iterator().next();
		if(n.isLiteral()) return ((KiWiLiteral)n).getContent();
		if(n.isUriResource()) return ((KiWiUriResource)n).getUri();
		if(n.isAnonymousResource()) return ((KiWiAnonResource)n).getAnonId();
		return n.toString();
  	}

}
